<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item
        ><a href="/admin" @click="resetDefaultActivePath"
          >首页</a
        ></el-breadcrumb-item
      >
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容卡片区域 -->
    <el-card class="box-card">
      <!-- 头部搜索区域 -->
      <el-form :model="searchData" class="demo-form-inline">
        <el-form-item style="padding-right: 20px">
          <el-select v-model="searchData.type" placeholder="">
            <el-option label="所有权限" value=""></el-option>
            <el-option label="菜单权限" value="menu"></el-option>
            <el-option label="路由权限" value="router"></el-option>
            <el-option label="请求权限" value="action"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="width: 100%">
          <el-input v-model="searchData.key" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item class="query_rights">
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="showAddRights">添加</el-button>
        </el-form-item>
      </el-form>
      <!-- 中间表格区域 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        :border="true"
        :stripe="true"
      >
        <el-table-column label="序号">
          <template #default="{ $index }">
            {{
              (searchData.currentPage - 1) * searchData.pageSize + $index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="rightsName" label="权限名称"> </el-table-column>
        <el-table-column prop="rightsDesc" label="权限描述"> </el-table-column>
        <el-table-column label="权限等级">
          <template #default="{ row }">
            <el-tag type="danger" v-if="row.level === 0">一级</el-tag>
            <el-tag type="warning" v-if="row.level === 1">二级</el-tag>
            <el-tag type="success" v-if="row.level === 2">三级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-switch
              v-model="row.rightsState"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="showEditRights(row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="destroyRights(row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--底部分页区域-->
    <el-pagination
      style="text-align: center; padding-top: 20px"
      :current-page="searchData.currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchData.pageSize"
      :total="totalCount"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>

    <!-- 新增编辑权限弹窗 -->
    <el-dialog
      :title="rightsData.id ? '编辑权限' : '新增权限'"
      :visible.sync="rightsDialogVisible"
      width="30%"
      @close="closeRights"
    >
      <el-form
        :model="rightsData"
        ref="formRights"
        :rules="rulesRights"
        label-width="70px"
      >
        <el-form-item label="权限名称" prop="rightsName">
          <el-input
            v-model="rightsData.rightsName"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限描述" prop="rightsDesc">
          <el-input
            v-model="rightsData.rightsDesc"
            prefix-icon="el-icon-info"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限状态">
          <el-switch v-model="rightsData.rightsState"></el-switch>
        </el-form-item>
        <el-form-item label="权限类型" prop="rightsType">
          <el-select
            v-model="rightsData.rightsType"
            placeholder="请选择权限类型"
          >
            <el-option label="菜单权限" value="menu"></el-option>
            <el-option label="路由权限" value="router"></el-option>
            <el-option label="请求权限" value="action"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限方法" prop="rightsMethod">
          <el-select
            v-model="rightsData.rightsMethod"
            :disabled="rightsData.rightsType !== 'action'"
            placeholder="请选择请求方法"
          >
            <el-option label="GET请求" value="get"></el-option>
            <el-option label="POST请求" value="post"></el-option>
            <el-option label="DELETE请求" value="delete"></el-option>
            <el-option label="PUT请求" value="put"></el-option>
            <el-option label="所有请求" value="all"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限等级" prop="level">
          <el-select v-model="rightsData.level" placeholder="请选择权限等级">
            <el-option label="一级权限" :value="0"></el-option>
            <el-option label="二级权限" :value="1"></el-option>
            <el-option label="三级权限" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级权限" prop="pid">
          <el-select
            v-model="rightsData.pid"
            :disabled="rightsData.level === 0"
            placeholder="请选择上级权限"
          >
            <el-option
              v-for="item in parentRights"
              :key="item.id"
              :label="item.rightsName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限地址" prop="rightsPath">
          <el-input
            v-model="rightsData.rightsPath"
            prefix-icon="el-icon-info"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSumbitRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  getRights,
  getAllRights,
  getRightInfo,
  getAddRights,
  delRights,
  updateRights,
} from "@/api";
import { ElForm } from "element-ui/types/form";
import { Component, Ref, Vue, Watch } from "vue-property-decorator";

interface SarchData {
  type: string;
  key: string;
  currentPage: number;
  pageSize: number;
}

interface RightsData {
  id: string;
  rightsName: string;
  rightsDesc: string;
  rightsType: string;
  rightsState: boolean;
  rightsMethod: string;
  rightsPath: string;
  pid: number;
  level: number;
}

@Component({
  name: "Rights",
  components: {},
})
export default class Rights extends Vue {
  private resetDefaultActivePath() {
    sessionStorage.removeItem("activePath");
  }
  private rightsDialogVisible = false; // 权限弹窗
  private parentRights: any[] = []; // 上级权限
  // 权限信息
  private rightsData: RightsData = {
    id: "", // 序号id
    rightsName: "", // 权限名称
    rightsDesc: "", // 权限描述
    rightsState: true, // 权限状态
    rightsType: "", // 权限类型
    rightsMethod: "", // 权限的请求方法
    rightsPath: "", // 权限地址
    pid: 0, // 父级id
    level: 0, // 权限等级
  };

  private validateMethod = (rule: any, value: string, callback: any) => {
    // 如果权限类型为 action 则不能为空
    if (this.rightsData.rightsType === "action" && !value) {
      callback("请求权限必须选择请求方式");
    } else {
      callback();
    }
  };

  private validatePid = (rule: any, value: number, callback: any) => {
    // 如果 level 不等于 0（一级）的话 上级权限也不能等于 0
    if (this.rightsData.level !== 0 && value === 0) {
      callback("非一级权限必须选择上级权限");
    } else {
      callback();
    }
  };

  // 权限校验规则
  private rulesRights = {
    rightsName: [
      { required: true, message: "请输入权限名称", trigger: "blur" },
      { min: 1, message: "长度至少 1 个字符", trigger: "blur" },
    ],
    rightsDesc: [
      { required: true, message: "请输入权限描述", trigger: "blur" },
      { min: 1, message: "长度至少 1 个字符", trigger: "blur" },
    ],
    rightsType: [
      { required: true, message: "请选择权限类型", trigger: "change" },
    ],
    rightsMethod: [{ validator: this.validateMethod, trigger: "change" }],
    rightsPath: [
      { required: false, message: "请输入权限地址", trigger: "blur" },
    ],
    pid: [{ validator: this.validatePid, trigger: "change" }],
    level: [{ required: false, message: "请选择权限等级", trigger: "change" }],
  };

  // 搜索相关代码
  private searchData: SarchData = {
    type: "",
    key: "",
    currentPage: 1,
    pageSize: 5,
  };

  // 总数量
  private totalCount = 0;

  // 权限列表
  private tableData: any[] = [
    // {
    //   rightsName: "菜单权限",
    //   rightsDesc: "是否可以使用特定菜单",
    //   level: 0,
    //   rightsState: true,
    // }
  ];
  @Ref() readonly formRights!: ElForm;

  private async created() {
    this.getRights();
  }

  // 获取权限列表
  private getRights() {
    getRights(this.searchData).then((response: any) => {
      // console.log(response);
      this.tableData = response.data.data.rights;
      this.totalCount = response.data.data.count;
    });
  }

  // 监听权限类型的变化来获取对应的权限列表
  @Watch("rightsData.rightsType", { deep: true })
  typeChange(newValue: any, oldValue: any) {
    if (newValue) {
      // 拿到最新的权限类型和它的上一个等级level  即使当前level为1 则取 0
      const obj = { rightsType: newValue, level: this.rightsData.level - 1 };
      // 获取其父级的权限菜单列表数据
      getRights(obj)
        .then((response: any) => {
          // console.log(response);
          this.parentRights = response.data.data.rights;
        })
        .catch((error) => {
          (this as any).$message.error(error.response.data.msg);
        });
    }
  }

  @Watch("rightsData.level", { deep: true })
  levelChange(newValue: any, oldValue: any) {
    if (newValue === 0) this.rightsData.pid = 0;
    if (newValue) {
      // 拿到最新的权限类型和它的上一个等级level  即使当前level为1 则取 0
      const obj = {
        rightsType: this.rightsData.rightsType,
        level: newValue - 1,
      };
      // 获取其父级的权限菜单列表数据
      getRights(obj)
        .then((response: any) => {
          // console.log(response);
          this.parentRights = response.data.data.rights;
        })
        .catch((error) => {
          (this as any).$message.error(error.response.data.msg);
        });
    }
  }

  // 查询按钮
  private onSubmit() {
    this.getRights();
  }

  // 添加按钮
  private showAddRights() {
    this.rightsDialogVisible = true;
  }

  // 新增或编辑权限确定按钮
  private onSumbitRights() {
    this.formRights.validate((valid: any) => {
      if (valid) {
        // 如果没有id, 则是新增权限
        if (!this.rightsData.id) {
          getAddRights(this.rightsData)
            .then((response: any) => {
              // console.log(response);
              if (response.status === 200) {
                this.getRights();
                this.rightsDialogVisible = false;
                (this as any).$message.success("新增权限成功");
              } else {
                (this as any).$message.error("新增权限失败");
              }
            })
            .catch((e) => {
              (this as any).$message.error(e.response.data.msg);
            });
        } else {
          // 编辑权限
          updateRights(this.rightsData.id, this.rightsData)
            .then((response: any) => {
              // console.log(response);
              if (response.status === 200) {
                this.getRights();
                this.rightsDialogVisible = false;
                (this as any).$message.success("编辑权限成功");
              } else {
                (this as any).$message.error("编辑权限失败");
              }
            })
            .catch((e) => {
              (this as any).$message.error(e.response.data.msg);
            });
        }
      } else {
        (this as any).$message.error("数据格式不正确");
      }
    });
  }

  // 编辑按钮
  private showEditRights(id: string) {
    this.rightsDialogVisible = true;
    // 获取单个权限信息用于回显数据
    getRightInfo(id).then((response: any) => {
      // console.log(response);
      this.rightsData = response.data.data;
    });
  }

  // 删除
  private destroyRights(id: string) {
    (this as any)
      .$confirm("确定删除该权限吗?", "提示", {
        // confirmButtonText: "确定",
        // cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        delRights(id)
          .then((response: any) => {
            // // 当前页如果剩下一条数据且页码大于1 则让页码减1
            if (
              this.tableData.length === 1 &&
              this.searchData.currentPage > 1
            ) {
              this.searchData.currentPage--;
            }
            // 刷新权限列表
            this.getRights();
            (this as any).$message({
              type: "success",
              message: "删除成功!",
            });
          })
          .catch((e: any) => {
            (this as any).$message.error(e.response.data.msg);
          });
      })
      .catch(() => {
        (this as any).$message({
          type: "info",
          message: "已取消删除",
        });
      });
  }

  // 关闭权限弹窗
  private closeRights() {
    // 清空数据
    this.rightsData = {
      id: "", // 序号id
      rightsName: "", // 权限名称
      rightsDesc: "", // 权限描述
      rightsState: true, // 权限状态
      rightsType: "", // 权限类型
      rightsMethod: "", // 权限的请求方法
      rightsPath: "", // 权限地址
      pid: 0, // 父级id
      level: 0, // 权限等级
    };
    // 重置表单
    this.formRights.resetFields();
  }
  // 分页相关代码
  private handleSizeChange(size: any) {
    this.searchData.pageSize = size;
    this.getRights();
  }

  private handleCurrentChange(current: any) {
    this.searchData.currentPage = current;
    this.getRights();
  }
}
</script>

<style lang="scss" scoped>
.el-breadcrumb {
  padding-bottom: 20px;
}
.demo-form-inline {
  display: flex;
  justify-content: center;
}
.query_rights {
  padding: 0 20px;
}
.el-pagination {
  padding-top: 20px;
}
</style>
